/***************************************************************************
* Copyright (C) 2008 by Lorenzo La Porta *
* lorelapo@gmail.com *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "Compress.h"
int compress(char *in, char *outn)
{
int i, j, c, res;
init_lett();
if((res=ana_freq(in))<0)
return -1;
create_template();
FILE *fp=fopen(in, "rb");
unlink(outn);
FILE *out=fopen(outn, "wb");
if(out==NULL)
return -2;
bitstream_t *bs=bitstream_new(out, 0);
for(i=0;i<257;i++)
{
for(j=0;j<6;j++)
bitstream_add_bit(bs, GETNBIT(stream[i].n, j));
for(j=0;j<stream[i].n;j++)
bitstream_add_bit(bs, GETNBIT(stream[i].w, j));
}
while((c=fgetc(fp))!=EOF)
{
for(i=0;i<stream[c&255].n;i++)
bitstream_add_bit(bs, GETNBIT(stream[c&255].w, i));
}
for(i=0;i<stream[256].n;i++)
bitstream_add_bit(bs, GETNBIT(stream[256].w, i));
bitstream_free(bs);
fclose(fp);
fclose(out);
free_redundtree(redundtree);
return 0;
}
int decompress(char *in, char *outn)
{
int i, j, c;
redundtree_t *decode;
FILE *fp=fopen(in, "rb");
if(fp==NULL)
return -1;
unlink(outn);
FILE *out=fopen(outn, "wb");
if(out==NULL)
return -2;
bitstream_t *bs=bitstream_new(fp, 1);
redundtree=redund_new();
decode=redundtree;
for(i=0;i<257;i++)
{
stream[i].n=0;
for(j=0;j<6;j++)
{
c=bitstream_read_bit(bs);
SETNBIT(stream[i].n, j, c);
}
for(j=0;j<stream[i].n;j++)
{
if(bitstream_read_bit(bs))
{
if(decode->dx==NULL)decode->dx=redund_new();
decode=decode->dx;
}
else
{
if(decode->sx==NULL)decode->sx=redund_new();
decode=decode->sx;
}
}
decode->c=i;
decode=redundtree;
}
decode=redundtree;
while(1)
{
c=bitstream_read_bit(bs);
if(c)
decode=decode->dx;
else
decode=decode->sx;
if(decode->sx==NULL&&decode->dx==NULL)
{
if(decode->c==256)break;
fputc(decode->c, out);
decode=redundtree;
}
}
bitstream_free(bs);
fclose(out);
fclose(fp);
free_redundtree(redundtree);
return 0;
}